<?php
/**
 * 微信消息推送
 *
 * @copyright  Copyright (c) 2015-2025 NcPHP Inc. (http://www.ncphp.com)
 * @license    http://www.ncphp.com/
 * @link       http://www.ncphp.com/
 * @author     NcPHP Team
 * @since      File available since Release v1.1
 */
defined('InNcPHP') or exit('Access Invalid!');

class wx_msgControl extends Control{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 微信消息推送入口
     */
    public function indexOp(){
        if ($this->checkSignature()) {
            if ($_SERVER['REQUEST_METHOD'] == 'GET') {
                echo $_GET['echostr'];
            } else {
                $this->responce();
            }
        }
    }

    /**
     * 处理微信消息推送
     */
    private function responce()
    {
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($obj) {
            $obj = json_decode(json_encode($obj), true);
            if ($obj['MsgType'] == 'event') {
                switch ($obj['Event']) {
                    case 'subscribe':
                        $openid = $obj['FromUserName'];
                        /** @var memberModel $model */
                        $model = Model('member');
                        $model->updateMember(array('openid'=>$openid), array('subscribe'=>1));
                        break;
                    case 'unsubscribe':
                        $openid = $obj['FromUserName'];
                        /** @var memberModel $model */
                        $model = Model('member');
                        $model->updateMember(array('openid'=>$openid), array('subscribe'=>0));
                        break;
                }
            }
        }
        echo 'success';
    }

    /**
     * 校验消息是否来自微信
     * @return bool
     */
    private function checkSignature()
    {
        $token = 'lvbangpiaowu';
        $signature = $_GET['signature'];
        $tmpArr = array($token, $_GET['timestamp'], $_GET['nonce']);
        sort($tmpArr, SORT_STRING);
        return $signature === sha1(implode($tmpArr));
    }
}
